<?php

class Api
{
    protected $noNeedLogin = [];

    protected $cookie = [];

    protected $userInfo;

    protected $isLogin = 0;

    protected $token;

    protected $isAdmin = 0;

    /**
     * @var $db MysqliDb
     */
    protected $db;


    public function __construct()
    {
        if (in_array($this->getParam('a'), $this->noNeedLogin)) {
            return;
        }
        $this->cookie = $_COOKIE;
        $this->token  = $this->cookie['token'];
        $userInfo     = Jwt::verifyToken($this->token);
        if (empty($userInfo)) {
            backJson([], ApiConst::BACK_NO_LOGIN);
        }
        if ($userInfo['expire'] < time()) {
            backJson([], ApiConst::BACK_LOGIN_EXPIRE);
        }
        if ((time() - $userInfo['time']) > 300) {
            $userInfo['time'] = time();
            setcookie('token', $this->token = Jwt::getToken($userInfo));
        }
        $this->initUserInfo($userInfo);
    }

    public function initUserInfo($userInfo = [])
    {
        if ($userInfo['name'] === 'admin') {
            $this->isAdmin = 1;
        }
        $this->userInfo = $userInfo;
        $this->isLogin  = $userInfo['id'];
    }

    public function getDb()
    {
        if (!$this->db) {
            $this->db = new Db();
        }
        return $this->db;
    }

    public function getParam($name, $default = null)
    {
        return getParam($name, postParam($name, inputParam($name, $default)));
    }

    public function backJson($data = [], $code = ApiConst::BACK_SUCCESS, $message = null)
    {
        backJson($data, $code, $message);
    }
}

$module = getParam('m');
if (file_exists(ACTION_PATH . $module . '.php')) {
    require ACTION_PATH . $module . '.php';
} else {
    backJson([], ApiConst::BACK_CODE_ERROR);
}
$action = getParam('a');
if (class_exists($module)) {
    $module = new $module();
    if (in_array($action, get_class_methods(get_class($module)))) {
        $module->$action();
    } else {
        backJson([], ApiConst::BACK_CODE_ERROR);
    }
} else {
    backJson([], ApiConst::BACK_CODE_ERROR);
}
